package com.ytaohui.serialport;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android_serialport_api.SerialPort;

public class MainActivity extends Activity {

	// 串口
	private SerialPort ttyS0port;
	private SerialPort ttyS1port;

	private OutputStream ttyS0outputStream;
	private InputStream ttyS0inputStream;

	private OutputStream ttyS1outputStream;
	private InputStream ttyS1inputStream;

	// 测试
	private TextView tv1;
	private EditText et1;

	private Handler han = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				tv1.append(msg.obj.toString() + "\n");
				break;
			case 2:
				tv1.append("ttyS0数据发送成功！" + "\n");
				break;
			case 3:
				tv1.append("ttyS0收到数据:" + msg.obj.toString() + "\n");
				break;
			case 4:
				tv1.append("ttyS1收到数据:" + msg.obj.toString() + "\n");
				break;
			case 5:
				tv1.append("ttyS1数据发送成功！" + "\n");
				break;
			default:
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();

		/*
		 * 串口初始化、打开、读写
		 */
		try {
			// 参数：驱动文件、波特率、文件权限(默认为0)
			ttyS0port = new SerialPort(new File("/dev/ttyS0"), 19200, 0);
			ttyS1port = new SerialPort(new File("/dev/ttyS1"), 19200, 0);
			
			// 获取读写流
			ttyS0inputStream = ttyS0port.getInputStream();
			ttyS0outputStream = ttyS0port.getOutputStream();
			ttyS1inputStream = ttyS1port.getInputStream();
			ttyS1outputStream = ttyS1port.getOutputStream();
			
			// 启动接收线程
			new TtyS0ReadThread().start();
			new TtyS1ReadThread().start();

			if (ttyS0port == null) {
				Message msg = new Message();
				msg.what = 1;
				msg.obj = "ttyS0串口打开失败！：port == null";
				han.sendMessage(msg);
			} else {
				Message msg = new Message();
				msg.what = 1;
				msg.obj = "串口ttyS0打开成功！";
				han.sendMessage(msg);
			}
			
			if (ttyS1port == null) {
				Message msg = new Message();
				msg.what = 1;
				msg.obj = "ttyS1串口打开失败！：port == null";
				han.sendMessage(msg);
			} else {
				Message msg = new Message();
				msg.what = 1;
				msg.obj = "串口ttyS1打开成功！";
				han.sendMessage(msg);
			}
		} catch (SecurityException e) {
			Message msg = new Message();
			msg.what = 1;
			msg.obj = "串口打开失败！:SecurityException";
			han.sendMessage(msg);

		} catch (IOException e) {
			Message msg = new Message();
			msg.what = 1;
			msg.obj = "串口打开失败！:IOException";
			han.sendMessage(msg);
		}

	}

	/**
	 * 初始化UI
	 */
	private void initView() {
		tv1 = (TextView) findViewById(R.id.textView1);

		et1 = (EditText) findViewById(R.id.editText1);

		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String data = et1.getText().toString();
				new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							ttyS0outputStream.write(data.getBytes());
							ttyS0outputStream.flush();
							Message msg = new Message();
							msg.what = 2;
							han.sendMessage(msg);
						} catch (IOException e) {

						}

					}
				}).start();
			}
		});
		
		
		
		findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				
				final String data = et1.getText().toString();
				new Thread(new Runnable() {

					@Override
					public void run() {

						try {
							ttyS1outputStream.write(data.getBytes());
							ttyS1outputStream.flush();
							Message msg = new Message();
							msg.what = 5;
							han.sendMessage(msg);

						} catch (IOException e) {

						}

					}
				}).start();
				
			}
		});
	}
	
	
	@Override
	protected void onDestroy() {
		
		//关闭串口
		
		if (ttyS0port != null) {
			
			ttyS0port.close();
			
		}
		
		
		if (ttyS1port != null) {
			ttyS1port.close();
		}
		
		
		super.onDestroy();
	}

	/**
	 * 读写线程
	 * 
	 * @author CYong
	 *
	 */
	private class TtyS0ReadThread extends Thread {

		public void run() {

			byte[] buffer = new byte[1024];
			synchronized (this) {
				while (true) {

					int length;
					try {
						length = ttyS0inputStream.read(buffer);
						if (length > 0) {

							String instruct = new String(buffer, 0, length);

							if (instruct.contains("]") && !instruct.contains("[")) {
								b = instruct;
							} else if (instruct.contains("[") && !instruct.contains("]")) {
								a = instruct;
							} else if (!instruct.contains("[") && !instruct.contains("]")) {
								c = instruct;
							} else if (instruct.contains("[") && instruct.contains("]")) {
								Message msg = Message.obtain();
								msg.what = 3;
								msg.obj = instruct;
								han.sendMessage(msg);
							}
							d = a + c + b;
							if (d.contains("[") && d.contains("]")) {
								Message msg = Message.obtain();
								msg.what = 3;
								msg.obj = d;
								han.sendMessage(msg);
								a = "";
								b = "";
								c = "";
								d = "";
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

				}
			}
		}
	}

	String a = "";
	String b = "";
	String c = "";
	String d = "";
	private class TtyS1ReadThread extends Thread {

		public void run() {

			byte[] buffer = new byte[1024];
			synchronized (this) {
				while (true) {

					int length;
					try {
						length = ttyS1inputStream.read(buffer);

						if (length > 0) {

							String instruct = new String(buffer, 0, length);

							if (instruct.contains("]") && !instruct.contains("[")) {
								b = instruct;
							} else if (instruct.contains("[") && !instruct.contains("]")) {
								a = instruct;
							} else if (!instruct.contains("[") && !instruct.contains("]")) {
								c = instruct;
							} else if (instruct.contains("[") && instruct.contains("]")) {
								Message msg = Message.obtain();
								msg.what = 4;
								msg.obj = instruct;
								han.sendMessage(msg);
							}
							d = a + c + b;
							if (d.contains("[") && d.contains("]")) {
								Message msg = Message.obtain();
								msg.what = 4;
								msg.obj = d;
								han.sendMessage(msg);
								a = "";
								b = "";
								c = "";
								d = "";
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

				}
			}
		}
	}

}
